package com.glela.platform.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.glela.api.im.rongcloud.ApiHttpClient;
import com.glela.api.im.rongcloud.vo.SdkHttpResult;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.beans.AreaCommonBean;
import com.glela.common.beans.FormatType;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.CommonConstants;
import com.glela.common.exception.BusinessError;
import com.glela.common.exception.BusinessException;
import com.glela.common.exception.InvalidArgumentException;
import com.glela.common.util.Config;
import com.glela.common.util.DateUtil;
import com.glela.common.util.IPUtils;
import com.glela.common.util.MassageInfo;
import com.glela.common.util.StringUtil;
import com.glela.constant.BizConstant;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.constant.ExceptionConstant;
import com.glela.platform.dao.IUserLocatedDao;
import com.glela.platform.mapper.CGuestMapper;
import com.glela.platform.mapper.CRoleMapper;
import com.glela.platform.mapper.ChangeProcessLogMapper;
import com.glela.platform.mapper.CheckCodeMapper;
import com.glela.platform.mapper.PromotionDetailMapper;
import com.glela.platform.mapper.PromotionMapper;
import com.glela.platform.mapper.TalentJobMapper;
import com.glela.platform.mapper.TokenMapper;
import com.glela.platform.mapper.UserFansMapper;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserJournalMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserPayInfoMapper;
import com.glela.platform.mapper.UserPromotionMapper;
import com.glela.platform.mapper.UserSetMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CRole;
import com.glela.platform.model.ChangeProcessLog;
import com.glela.platform.model.CheckCode;
import com.glela.platform.model.GivePromotionHistory;
import com.glela.platform.model.GivePromotionList;
import com.glela.platform.model.Guest;
import com.glela.platform.model.MyInvitationFriend;
import com.glela.platform.model.MyattentionTalent;
import com.glela.platform.model.TalentJob;
import com.glela.platform.model.User;
import com.glela.platform.model.UserFans;
import com.glela.platform.model.UserGuest;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserLocatedInfo;
import com.glela.platform.model.UserPayInfo;
import com.glela.platform.model.request.RequestBaseModel;
import com.glela.platform.model.request.RequestGuest;
import com.glela.platform.model.request.RequestUserModel;
import com.glela.platform.model.request.RequsetPersonalInfo;
import com.glela.platform.model.response.MemberFeeAndTotalSale;
import com.glela.platform.model.response.ReponseUserTeacher;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseMineInfoModel;
import com.glela.platform.model.response.ResponsePersonalInfoset;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseTeacher;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.model.response.ResponseUserVo;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.TokenService;
import com.glela.platform.service.UnifiedTreatmentService;
import com.glela.platform.service.UserMoneyService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import com.glela.platform.util.UserUtil;
import com.glela.sensitiveWords.service.SensitiveWordsFilterService;

/**
 * @author liujie
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Resource
	private UserMapper userMapper;
	@Resource
	private UserJournalMapper userJournalMapper;
	@Resource
	private UserPromotionMapper userPromotionMapper;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private CheckCodeMapper checkCodeMapper;
	@Resource
	private UserSetMapper userSetMapper;
	@Resource
	private TokenMapper tokenMapper;
	@Autowired
	private CRoleMapper cRoleMapper;
	@Autowired
	private IUserLocatedDao userLocatedDao;
	@Autowired
	SensitiveWordsFilterService sensitiveWordsFilterService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	CGuestMapper guestMapper;
	@Resource
	private UserFansMapper userFansMapper;
	@Resource
	private PromotionDetailMapper promotionDetailMapper;
	@Resource
	private PromotionMapper promotionMapper;
	@Autowired
	private UnifiedTreatmentService unifiedTreatmentService;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private TalentJobMapper talentJobMapper;
	@Autowired
	private ChangeProcessLogMapper LogMapper;
	@Autowired
	private UserPayInfoMapper userPayInfoMapper;
	@Autowired
	private UserMoneyService userMoneyService;
	@Autowired
	private RedisUtil redisUtil;
	

	private static ExecutorService executorService = Executors.newFixedThreadPool(20);

	@Override
	public int bindGuestUser(Long userId, String guestCode) {
		/**********************************************************/
		/****** BEGIN MODIFY 修改绑定数量 liujie *************/
		/**********************************************************/
		// 一台设备上所能绑定的用户数量
		int guestUserLimit = 1;
		/**********************************************************/
		/****** END MODIFY 修改绑定数量 liujie *************/
		/**********************************************************/

		Guest guest = guestMapper.selectByCode(guestCode);
		if (guest == null) {// 找不到匿名用户
			logger.error("数据异常，找不到匿名用户");
			return 0;
		}
		Long guestId = guest.getId();
		int size = userMapper.selectGuestUserSize(userId, guestId);
		if (size <= guestUserLimit) {
			userMapper.insertUserGuest(userId, guestId);
			// 初次绑定，资产归集
			// if (result > 0)
			// result = collectionAssets(guestId, userId);
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public User getUser(Long id) {
		if (id == null || id == 0l) {
			return null;
		}
		User user = userMapper.selectByPrimaryKey(id);

		return user;
	}

	@Override
	public ResponseUser getUserByName(String userName) {
		if (StringUtils.isEmpty(userName)) {
			return null;
		}
		return userMapper.selectUserByUserNameNopassword2(userName);
	}

	@Override
	public UserGuest getUserGuestByGuestId(Long guestId) {
		return userMapper.selectUserGuestByGuestId(guestId);
	}

	public UserMapper getUserMapper() {
		return userMapper;
	}

	/**
	 * 退出登录
	 */
	@Override
	public int logOut(Long userId, String clientType) {
		int res = tokenMapper.deleteByLogOut(userId, clientType);

		return res;
	}

	@Override
	public Long queryUserId(RequestBaseModel model) {
		Long userId = model.getUserId();
		if (userId == null || userId == 0) {
			Guest guest = guestMapper.selectByCode(model.getGuestId());
			if (guest != null) {
				userId = guest.getId();

				// 若存在绑定关系，匿名用户直接替换成其绑定用户
				UserGuest ug = userMapper.selectUserGuestByGuestId(userId);
				if (ug != null)
					userId = ug.getUserId();
			}
		}
		return userId;
	}

	/**
	 * 用户注册
	 * 
	 * @throws Exception
	 */
	@Override
	public int saveRegister(RequestUserModel userModel) throws Exception {
		// // int res = 0;
		// // // 添加用户并获取插入的id
		// // User user = new User();
		// // user.setUserName(userModel.getUserName());
		// // user.setPassword(userModel.getPassword());
		// // String username = userModel.getUserName();
		// // if (username == null || "".equals(username)) {
		// // username = userModel.getMobilePhone();
		// // }
		// // user.setUserName(username);
		// // user.setNickName(userModel.getMobilePhone());
		// // // user.setType(userModel.getType());
		// // // user.setGrade(1);
		// // // user.setCreditStatus(0);
		// // user.setLockStatus(0);
		// // if (selectFlag("ali_query") == 1) {
		// // Boolean f = AliQueryUtil.isBlack(userModel.getUserIp(), username,
		// // AliQueryUtil.SCENE_REGISTER, this);
		// // if (f != null) {
		// // user.setIsBlack(f ? 1 : 0);
		// // }
		// // }
		// //
		// user.setCreateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// //
		// user.setUpdateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// //
		// user.setLastLoginTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// // res = userMapper.insertSelective(user);
		// // if (0 == res) {
		// // throw new Exception();
		// // }
		// // Long id = user.getId();
		// //
		// // UserInfo userInfo = new UserInfo();
		// // userInfo.setUserId(id);
		// // /*
		// // * add by liujie 2016-03-16 增加注册渠道
		// // */
		// // res = userInfoMapper.insertSelective(userInfo);
		// // if (0 == res) {
		// // throw new Exception();
		// // }
		// // // 初始化用户设置
		// // UserSet userSet = new UserSet();
		// //
		// userSet.setCreateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// // // TODO
		// // userSet.setDeviceId(null);
		// // userSet.setUserId(id);
		// // userSet.setAttentionSwitch(1);
		// // userSet.setMsgSwitch(1);
		// // res = userSetMapper.insertSelective(userSet);
		// // if (0 == res) {
		// // throw new Exception();
		// // }
		// // // 初始化用户资产
		// // // IntegralAssets integralAssets = new IntegralAssets();
		// // //
		// //
		// integralAssets.setCreateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// // //
		// //
		// integralAssets.setUpdateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// // // integralAssets.setTotal(0);
		// // // integralAssets.setUserId(id);
		// //
		// // // res = integralAssetsMapper.insertSelective(integralAssets);
		// // if (0 == res) {
		// // throw new Exception();
		// // }
		// //
		// // userModel.setUserId(id);
		//
		// UserInfo userInfo = new UserInfo();
		// userInfo.setUserId(id);
		// /*
		// * add by liujie 2016-03-16 增加注册渠道
		// */
		// // userInfo.setRegisterChannel(userModel.getChannelId());
		// res = userInfoMapper.insertSelective(userInfo);
		// if (0 == res) {
		// throw new Exception();
		// }
		// // 初始化用户设置
		// UserSet userSet = new UserSet();
		// userSet.setCreateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// // TODO
		// userSet.setDeviceId(null);
		// userSet.setUserId(id);
		// userSet.setAttentionSwitch(1);
		// userSet.setMsgSwitch(1);
		// res = userSetMapper.insertSelective(userSet);
		// if (0 == res) {
		// throw new Exception();
		// }
		// // 初始化用户资产
		// // IntegralAssets integralAssets = new IntegralAssets();
		// //
		// //
		// integralAssets.setCreateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// //
		// //
		// integralAssets.setUpdateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// // integralAssets.setTotal(0);
		// // integralAssets.setUserId(id);
		//
		// // res = integralAssetsMapper.insertSelective(integralAssets);
		// if (0 == res) {
		// throw new Exception();
		// }
		//
		// userModel.setUserId(id);

		return 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.glela.service.UserService#selectSystemFlag(java.lang.String)
	 */
	@Override
	public int selectSigninFlag() {
		// 获取签到活动开关状态
		int res = userMapper.selectSystemFlag("openSignin");
		if (res != ExceptionConstant.OPERATION_SUCC) {// 签到关闭
			return 0;
		}
		return 1;
	}

	@Override
	public long selectUserIdByPhoneNumber(String PhoneNumber) {
		Long id = userMapper.selectIdByMobilePhone(PhoneNumber);
		if (id != null) {
			return id;
		} else {
			return 0;
		}
	}

	/**
	 * 查询用户是否已被注册（根据用户名）
	 */
	@Override
	public int selectUserIdByUserName(String mobilePhone) {
		Long id = userMapper.selectIdByUserName(mobilePhone);
		if (null != id) {
			return 1;
		} else {
			return 0;
		}
	}

	/**
	 * 查询个人设置信息
	 * 
	 * @param userId
	 * @return
	 */
	@Override
	public ResponsePersonalInfoset selectUserPicture(Long userId) {
		ResponsePersonalInfoset personalInfo = userInfoMapper.selectUserPicture(userId);
		if (personalInfo != null) {
			if (personalInfo.getGrade() == null) {
				personalInfo.setGrade(0);
			}
			personalInfo.setPicture(Config.getString("qiniu.http.base", "") + personalInfo.getPicture());
		}
		return personalInfo;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	/**
	 * 用户登录
	 * 
	 * @throws Exception
	 */
	@Override
	public ResponseUser updateLogin(RequestUserModel userModel) throws Exception {
		/*
		 * User user = new User(); user.setUserName(userModel.getUserName());
		 * user.setPassword(userModel.getPassword());
		 * user.setUserMachineCode(userModel.getUserMachineCode()); ResponseUser res =
		 * userMapper.login(null); if (null == res) { return res; }
		 */

		User loginUser = userMapper.getUserByName(userModel.getUserName());

		if (loginUser == null) {
			return null;
		}
		if (!loginUser.getPassword().equals(userModel.getPassword())) {
			return null;
		}

		UserInfo userInfo = userInfoMapper.selectUserInfoByUserId(loginUser.getId());

		if (userInfo == null) {
			return null;
		}

		CRole role = cRoleMapper.selectByPrimaryKey(loginUser.getRoleId());

		if (role == null) {
			return null;
		}

		ResponseUser responseUser = new ResponseUser();
		responseUser.setUserId(loginUser.getId());
		responseUser.setUserName(loginUser.getUserName());
		responseUser.setRoleId(loginUser.getRoleId());
		responseUser.setNickName(loginUser.getNickName());
		responseUser.setLockStatus(loginUser.getLockStatus());
		responseUser.setIsBlack(loginUser.getIsBlack());
		responseUser.setIsStore(loginUser.getIsStore());
		responseUser.setStoreId(loginUser.getStoreId());
		responseUser.setMoney(Long.valueOf(loginUser.getMoney() + ""));
		responseUser.setSynopsis(loginUser.getSynopsis());
		responseUser.setTalentEffectTime(loginUser.getTalentEffectTime());
		responseUser.setTalentFailureTime(loginUser.getTalentFailureTime());
		responseUser.setPicture(loginUser.getPicture());
		responseUser.setRecommendFrom(loginUser.getRecommendFrom());
		responseUser.setMemberRecommend(loginUser.getMemberRecommend());
		responseUser.setTalentTeacher(loginUser.getTalentTeacher());
		responseUser.setIsOpenRecommand(loginUser.getIsOpenRecommand());

		responseUser.setRealName(userInfo.getRealName());
		responseUser.setPersionId(userInfo.getPersionId());
		responseUser.setSex(userInfo.getSex());
		responseUser.setLocatedName(userInfo.getLocatedName());

		responseUser.setLevel(role.getLevel());
		responseUser.setRoleCode(role.getRoleCode());
		responseUser.setRoleName(role.getRoleName());

		User updateUser = new User();

		updateUser.setId(loginUser.getId());
		updateUser.setUserMachineCode(userModel.getUserMachineCode());
		userMapper.updateByLogin(updateUser);

		return responseUser;
	}

	/**
	 * 重置密码
	 */
	@Override
	public ResponseUser updatePassword(RequestUserModel userModel) {
		User user = new User();
		user.setPassword(userModel.getPassword());
		user.setUserName(userModel.getUserName());
		int res = userMapper.updatePasswordByMobilePhone(user);
		if (0 == res) {
			return null;
		}
		user.setUserName(userModel.getMobilePhone());
		ResponseUser resulet = userMapper.login(user);
		return resulet;
	}

	/**
	 * 修改密码
	 */
	@Override
	public int updatePasswordByChange(RequestUserModel userModel) {
		// User user = new User();
		// user.setUserName(userModel.getUserName());
		// user.setPassword(userModel.getPassword());
		// ResponseUser res = userMapper.login(user);
		// if (null == res) {
		// return 0;
		// }
		// user.setId(res.getId());
		// user.setPassword(userModel.getNewPass());
		// user.setUpdateTime(DateUtils.getNowDate(DateUtils.DATE_TIME_FORMAT));
		// int result = userMapper.updateByPrimaryKeySelective(user);
		// if (0 == result) {
		// return 0;
		// }
		return 1;
	}

	@Override
	public User selectRecommendFromByUserId(Long id) {
		// return id == null ? null : userMapper.selectRecommendFromByUserId(id);
		User u = userMapper.selectByPrimaryKey(id);
		if (u != null) {
			return userMapper.selectRecommendFromByPersionId(u.getRecommendFrom());
		}
		return null;
	}

	/**
	 * 修改个人设置信息
	 * 
	 * @param user
	 * @param picture
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean updateUserInfoset(RequsetPersonalInfo requsetPersonalInfo) throws Exception {

		boolean flage = false;
		UserInfo userInfo = new UserInfo();
		if (!ParameterUtils.validParams(requsetPersonalInfo.getRealName())) {
			userInfo.setRealName(requsetPersonalInfo.getRealName());
		}
		if (!ParameterUtils.validParams(requsetPersonalInfo.getAge())) {
			userInfo.setAge(requsetPersonalInfo.getAge());
		}
		if (!ParameterUtils.validParams(userInfo.getRealName()) || !ParameterUtils.validParams(userInfo.getSex()) || !ParameterUtils.validParams(userInfo.getAge())) {
			userInfo.setUserId(requsetPersonalInfo.getUserId());
			userInfoMapper.updateByUserIdSelective(userInfo);
			flage = true;
		}
		User user = new User();
		if (!ParameterUtils.validParams(requsetPersonalInfo.getNickName())) {
			user.setNickName(requsetPersonalInfo.getNickName());
		}
		if (StringUtils.isNotBlank(user.getNickName()) && !sensitiveWordsFilterService.checkSensitiveWords(user.getNickName())) {
			throw new InvalidArgumentException(BusinessError.C0000_0003, MassageInfo.C_USER_NICKNAME_INCLUDE_SENSITIVE_WORDS);
		}
		// if (!ParameterUtils.validParams(requsetPersonalInfo.getEmail())) {
		// user.setEmail(requsetPersonalInfo.getEmail());
		// }
		// if
		// (!ParameterUtils.validParams(requsetPersonalInfo.getMobilePhone())) {
		// user.setMobilePhone(requsetPersonalInfo.getMobilePhone());
		// }
		// if (!ParameterUtils.validParams(user.getNickName()) ||
		// !ParameterUtils.validParams(user.getEmail())
		// || !ParameterUtils.validParams(user.getMobilePhone())) {
		if (!ParameterUtils.validParams(user.getNickName())) {
			user.setId(requsetPersonalInfo.getUserId());
			userInfoMapper.updateCuserByUserId(user);
			flage = true;
		}

		return flage;

	}

	// 获取用户当前位置
	@Override
	public String getCurrentCode(String ip) {
		String[] area = null;
		String city = "";
		try {
			area = IPUtils.find(ip);
			city = area[2];
		} catch (Exception e) {
			logger.error("定位失败，ip：" + ip, e);
			return "";
		}
		List<AreaCommonBean> beans = userLocatedDao.selectAreaByName(city);
		if (beans == null || beans.size() == 0) {
			// 区域无效
			return "";
		}
		AreaCommonBean areaBean = beans.get(0);
		return areaBean.getFullCode();
	}

	private void insertUserLocInfo(boolean hasUserInfo, long userId, String currentCode) {
		// 新增info 更新用户的常驻地
		if (!hasUserInfo) {
			UserInfo userInfo = new UserInfo();
			userInfo.setUserId(userId);
			userInfo.setLocated(currentCode);
			// 插入用户信息
			userInfoMapper.insertSelective(userInfo);
		} else {
			userLocatedDao.updateUserLocated(userId, currentCode);
		}
		// 重新插入 定位信息
		UserLocatedInfo userLocatedInfo = new UserLocatedInfo();
		userLocatedInfo.setLocated(currentCode);
		userLocatedInfo.setNum(1);
		userLocatedInfo.setUserId(userId);
		userLocatedDao.insertUserLocatedInfo(userLocatedInfo);
	}

	private void updateUserLocInfo(UserLocatedInfo userLocatedInfo, String currentCode, String located) {
		long userId = userLocatedInfo.getUserId();
		int newNum = userLocatedInfo.getNum() + 1;
		userLocatedInfo.setNum(newNum);
		userLocatedDao.updateUserLocatedInfo(userLocatedInfo);
		// 判断是否可以进行覆盖
		if (newNum >= CommonConstants.UPDATE_USER_LOCATED_NUM) {
			// 进行地理位置的覆盖
			if (!currentCode.equals(located)) {
				userLocatedDao.updateUserLocated(userId, currentCode);
			}
		}
	}

	@Override
	public int setUserLocated(long userId, String ip) throws BusinessException {
		if (userId <= 0 || StringUtil.isEmpty(ip)) {
			throw new BusinessException(BusinessError.C8888, ExceptionConstant.INVALID_ARGUMENT);
		}
		String currentCode = getCurrentCode(ip);
		// 获取当前用户信息
		User user = userMapper.selectByPrimaryKey(userId);
		if (user == null) {
			throw new BusinessException(BusinessError.C8888, ExceptionConstant.USER_NO_EXIST);
		}
		// 用户基本信息获取
		UserInfo userInfo = userInfoMapper.selectByUserId(userId);
		// 尚未定位
		if (userInfo == null) {
			if (StringUtils.isEmpty(currentCode)) {
				// 首次定位默认上海
				currentCode = CommonConstants.SH;
			}
			insertUserLocInfo(false, userId, currentCode);
			return CommonConstants.SUCCESS_RES;
		}
		// 当前位置
		String located = userInfo.getLocated();

		UserLocatedInfo userLocatedInfo = userLocatedDao.getUserLocatedInfo(userId);
		// 当前未定位
		if (StringUtil.isEmpty(located) || userLocatedInfo == null) {
			// 新增info 更新用户的常驻地
			if (StringUtils.isEmpty(currentCode)) {
				// 首次定位默认上海
				currentCode = CommonConstants.SH;
			}
			insertUserLocInfo(true, userId, currentCode);
		} else {// 已经被定位
			String locationCode = userLocatedInfo.getLocated();
			if (currentCode.equals(locationCode)) {
				updateUserLocInfo(userLocatedInfo, currentCode, located);
			} else {
				// 令其现场进行归档调用 不影响当前线程
				new Thread(new RecordThread(userLocatedInfo, currentCode)).start();
			}
		}
		return CommonConstants.SUCCESS_RES;
	}

	@Override
	public int setGuestLocated(Guest guest, String ip) throws BusinessException {
		if (StringUtil.isEmpty(ip)) {
			throw new BusinessException(BusinessError.C8888, ExceptionConstant.INVALID_ARGUMENT);
		}
		if (guest == null) {
			throw new BusinessException(BusinessError.C8888, ExceptionConstant.USER_NO_EXIST);
		}
		Long guestId = guest.getId();
		String currentCode = getCurrentCode(ip);
		// 当前位置
		String located = guest.getLocated();

		UserLocatedInfo userLocatedInfo = userLocatedDao.getUserLocatedInfo(guestId);
		// 当前未定位
		if (userLocatedInfo == null) {
			// 新增info 更新用户的常驻地
			if (StringUtils.isEmpty(currentCode)) {
				// 首次定位默认上海
				currentCode = CommonConstants.SH;
			}
			guest.setLocated(currentCode);
			userLocatedInfo = new UserLocatedInfo();
			userLocatedInfo.setLocated(currentCode);
			userLocatedInfo.setNum(1);
			userLocatedInfo.setUserId(guestId);
			userLocatedDao.insertUserLocatedInfo(userLocatedInfo);
		} else {// 已经被定位
			String locationCode = userLocatedInfo.getLocated();
			if (currentCode.equals(locationCode)) {
				int newNum = userLocatedInfo.getNum() + 1;
				userLocatedInfo.setNum(newNum);
				userLocatedDao.updateUserLocatedInfo(userLocatedInfo);
				// 判断是否可以进行覆盖
				if (newNum >= CommonConstants.UPDATE_USER_LOCATED_NUM) {
					// 进行地理位置的覆盖
					if (!currentCode.equals(located)) {
						guest.setLocated(currentCode);
					}
				}
			} else {
				// 令其现场进行归档调用 不影响当前线程
				new Thread(new RecordThread(userLocatedInfo, currentCode)).start();
			}
		}
		return CommonConstants.SUCCESS_RES;
	}

	/*
	 * 
	 * 归档用户地理位置信息 (non-Javadoc)
	 * 
	 * @see com.glela.service.UserService#recordUserLocatedInfo(com.glela.platform.
	 * model.UserLocatedInfo, java.lang.String)
	 */
	@Override
	public int recordUserLocatedInfo(UserLocatedInfo userLocatedInfo, String currentCode) {
		long userId = userLocatedInfo.getUserId();
		// 地理位置信息归档
		userLocatedDao.addUserLocatedRecord(userLocatedInfo);
		// 清空当前定位表
		userLocatedDao.removeUserLocatedInfo(userId);

		// 重新插入 定位信息
		userLocatedInfo.setLocated(currentCode);
		userLocatedInfo.setNum(1);
		;
		userLocatedInfo.setUserId(userId);
		// 保存当前定位信息
		userLocatedDao.insertUserLocatedInfo(userLocatedInfo);
		return CommonConstants.SUCCESS_RES;
	}

	class RecordThread implements Runnable {
		private UserLocatedInfo userLocatedInfo;
		private String currentCode;

		RecordThread(UserLocatedInfo userLocatedInfo, String currentCode) {
			this.currentCode = currentCode;
			this.userLocatedInfo = userLocatedInfo;
		}

		@Override
		public void run() {
			// 归档操作
			recordUserLocatedInfo(userLocatedInfo, currentCode);
		}

	}

	@Override
	public boolean isNewDevice(String deviceCode) {
		int n = userMapper.isNewDevice(deviceCode);
		return n == 0 ? true : false;
	}

	@Override
	public boolean isNewUser(Long userId) {
		int n = userMapper.isNewUser(userId);
		return n == 0 ? true : false;
	}

	/****** BEGIN getDeviceLink BY 20160309 liujie **********/
	/**
	 * 获取设备标识 modify by liujie 2016-03-30 拆表 设备信息从设备表获取
	 * 
	 * @param gusetId
	 * @return
	 */
	@Override
	public String getDeviceLinkByGuestId(RequestGuest param) {
		String gusetId = param.getGuestId();
		String result = "";
		try {
			Guest guest = guestMapper.selectByCode(gusetId);
			result = guest.getCode();
		} catch (Exception e) {
			result = "";
			logger.error("调用数据库获取deviceLink发生异常：", e);
		}
		return result;
	}

	/**
	 * 更新设备信息 modify by zcl 2016-03-09
	 * 
	 * @param gusetId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public int updateGuestInfo(Guest guest) {
		return guestMapper.update(guest);
	}

	/****** END getDeviceLink BY 20160309 liujie **********/
	@Transactional(rollbackFor = Exception.class)
	@Override
	public int updateUser(User user) {
		return userMapper.updateByPrimaryKeySelective(user);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int insertIpQueryLog(String mobile, String ip, String scene, String result) {
		return userMapper.insertIpQueryLog(mobile, ip, scene, result);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.glela.service.UserService#selectFlag(java.lang.String)
	 */
	@Override
	public int selectFlag(String key) {
		return userMapper.selectSystemFlag(key);
	}

	/**
	 * 查询我的功能
	 */
	@Override
	public ResponseMineInfoModel selectMineInfo(long userId, String clickDate) {
		ResponseMineInfoModel PersonalInfo = new ResponseMineInfoModel();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (StringUtil.isNotEmpty(clickDate)) {
			sdf.format(new Date(Long.parseLong(clickDate)));
		}
		PersonalInfo = userInfoMapper.selectPersonIMainInfo(userId);
		if (StringUtil.isNotEmpty(PersonalInfo.getHeadPortrait())) {
			String headPortrait = Config.getString("qiniu.http.base") + PersonalInfo.getHeadPortrait();
			PersonalInfo.setHeadPortrait(headPortrait);
		}
		return PersonalInfo;
	}

	/**
	 * 修改余额
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateUserInfonickMoneyById(long id, int money) {
		userMapper.updateUserInfonickMoneyById(id, money);
	}

	/**
	 * 根据用户id查询用户信息
	 * 
	 * @param Id
	 * @return
	 */
	@Override
	@Transactional
	public User getUserEntityByIdNoPassword(long userId) throws Exception {
		// TODO Auto-generated method stub
		User user = userMapper.selectUserEntityByIdNoPassword(userId);
		if (user == null) {// 判断用户是否存在
			return null;
		}
		userMapper.updateUserTotalSale(unifiedTreatmentService.userSalesAmountTotal(userId), userId);
		BaseRestrictions baseRestrictions = baseRestrictionsService.selectAllBaseRestrictionsByType("upgrade_store_ grade_value");
		// 暂时注释满1000升级为标准店逻辑
		if (Objects.equals(baseRestrictions, null)) {
			throw new Exception("未设置标准店升级业绩标准！");
		}
		// upgrade_store_grade_value 小白店铺升级为标准店铺的业绩门槛：单位：分
		int upgrade_store_grade_value = baseRestrictions.getRestrictions();

		if (user.getTotalSale() < upgrade_store_grade_value) {
			user.setRemainSalesQuota(upgrade_store_grade_value - user.getTotalSale());
		}
		if (user.getTotalSale() >= upgrade_store_grade_value && user.getTotalSale() < CommonConstants.SYSTEM_MAX_TOTAL_AMOUNT) {
			user.setRemainSalesQuota(CommonConstants.SYSTEM_MAX_TOTAL_AMOUNT - user.getTotalSale());
		}
		UserInfo userInfo = userInfoMapper.selectUserInfoEntityByUserId(userId);
		user.setUserInfo(userInfo);
		user.setRongCloudToken("");
		// 计算当前用户 ：userId ，累计业绩，计算逻辑：交易成功的订单，（行）支付金额 ＋ （行）优惠金额
		// int i = userMapper.selectOrderDetailByUserIdSumTotalFee(userId);
		// if (user.getRoleId() < 2) {
		// if (i >= 29900) {
		// // 将用户ROLEID ： 1（普通用户）更新用户的ROLEID 为 2 （会员）
		// userMapper.updateUserRoseIdByUserId(user.getId(),
		// DateUtil.toString(new Date()), "2049-12-30 00:00:00");
		// }
		// }

		if (user.getRoleId() < 3) {
			user.setTotalSale(0);
		} else {
			user.setTotalSale(unifiedTreatmentService.userSalesAmountTotal(userId));
		}
		return user;
	}

	/**
	 * 注册用户
	 * 
	 * @param
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int userRegistration(String userName, String password, String code, int regSource) {
		// TODO Auto-generated method stub
		/*
		 * 2018-03-07 by tangcl 修改 persionId = 'X' + userId, sign = userId int sign =
		 * userInfoMapper.selectUserinfoMaxSign(); if (sign <= 0) { sign = 100000; }
		 * sign += 1; String persionId = RandomUtil.getRandomStr(2) + sign;
		 */
		String recommendFrom = "";
		// 校妆姐姐店铺的店主ID
		Integer storeUserId = this.baseRestrictionsService.getBaseRestrictionsForCache("xz_jj").getExperience();
		// 默认普通推荐人身份为校妆姐姐
		if (storeUserId != null) {
			UserInfo xzjjUserInfo = userInfoMapper.selectByUserId(Long.valueOf(storeUserId));
			if (xzjjUserInfo != null) {
				recommendFrom = xzjjUserInfo.getPersionId();
			}
		}
		User user = userMapper.selectUserByUserName(userName);
		if (user != null) {
			int i = 2;
			return i;
		}
		CheckCode checkcode = checkCodeMapper.selectCheckCodeByMobile(userName);
		if (!checkcode.getCode().equals(code)) {
			int i = 3;
			return i;
		}

		int i = userMapper.insertUser(userName, password, recommendFrom, "", "");

		if (i > 0) {// 注册成功 开始记录日志
			ChangeProcessLog Log = new ChangeProcessLog();
			Log.setDescription("用户注册");
			Log.setMethod("UserServiceImpl.userRegistration");
			Log.setPrimaryID("");
			Log.setTableName("yg_user.c_user");
			Log.getAfterMap().put("recommendFrom", recommendFrom);
			LogMapper.insert(Log);
		}

		User user1 = userMapper.selectUserByUserName(userName);
		// 检查是否存在usermoney信息
		userMoneyService.checkExistUserMoney(user1.getId());

		userInfoMapper.insertUserInfoNew(user1.getId(), UserUtil.getPersonId(user1.getId()), user1.getId().intValue(), 0, regSource);
		/*
		 * UserPromotion userPromotion = new UserPromotion(); Promotion promotion =
		 * promotionMapper.selectByPrimaryKey(25); List<PromotionDetail>
		 * listPromotionDetail = promotionDetailMapper
		 * .selectPromotionDetailByPromotionId(promotion.getId()); for (PromotionDetail
		 * promotionDetail : listPromotionDetail) {
		 * userPromotion.setPromotionId(promotionDetail.getPromotionId());
		 * userPromotion.setPromotionDetailId(promotionDetail.getId());
		 * userPromotion.setType(promotionDetail.getType());
		 * userPromotion.setPromotionDetailName(promotionDetail
		 * .getPromotionDetailName()); userPromotion.setUserId(user1.getId());
		 * userPromotion.setBrandId(promotionDetail.getBrandId());
		 * userPromotion.setGoodId(promotionDetail.getGoodId());
		 * userPromotion.setLimited(promotionDetail.getLimited());
		 * userPromotion.setIsDiscount(promotionDetail.getIsDiscount());
		 * userPromotion.setAmount(promotionDetail.getAmount());
		 * userPromotion.setEffectiveTime(promotionDetail.getEffectiveTime());
		 * userPromotion .setExpirationTime(promotionDetail.getExpirationTime());
		 * userPromotion.setPromotionNumber(1);
		 * userPromotion.setTargetSelfType(promotionDetail.getTargetSelfType());
		 * userPromotion.setDiscount(promotionDetail.getDiscount());
		 * userPromotionMapper.insertUserPromotion(userPromotion); }
		 */
		// 优惠券过期时间
		Integer expirationDay = this.baseRestrictionsService.getBaseRestrictionsForCache("expiration_day").getExperience();
		String jobNo = "0";
		TalentJob talentJob = talentJobMapper.selectTalentJobByUserId(user1.getId());
		if (talentJob != null) {
			jobNo = talentJob.getJobNo();
		}
		Date nowDate = DateUtil.toDate(System.currentTimeMillis());
		// 优惠券礼包赠送主表
		GivePromotionList givePromotionList = new GivePromotionList();
		givePromotionList.setTearchUserId(storeUserId);
		givePromotionList.setTearchJobNo(jobNo);
		givePromotionList.setGiveTime(nowDate);
		givePromotionList.setPromotionId(25);
		givePromotionList.setAdminUserId(0);
		givePromotionList.setNums(1);
		// this.givePromotionListMapper.insertAndGetId(givePromotionList);
		// 优惠券礼包赠送附表
		GivePromotionHistory gph = new GivePromotionHistory();
		gph.setTearchUserId(Long.valueOf(storeUserId));
		gph.setTearchJobNo(jobNo);
		gph.setAdminUserId(0L);
		gph.setUserId(user1.getId());
		gph.setUserRoleId(Long.valueOf(user1.getRoleId()));
		gph.setPromotionId(25L);
		gph.setGiveTime(nowDate);
		gph.setExpirationTime(DateUtil.parse(DateUtil.getFewDays(expirationDay)));
		gph.setStatus(1);
		gph.setpId(givePromotionList.getId());
		// this.givePromotionHistoryMapper.insertSelective(gph);
		return i;
	}

	/**
	 * 重置密码
	 * 
	 * @param Id
	 * @return
	 */
	@Override
	public int updateUserPasswordById(long userId, String password, String newPassword) {
		// TODO Auto-generated method stub
		int i;
		User user = userMapper.selectUserEntityById(userId);
		if (user == null) {
			i = 300;
			return i;
		}
		if (!user.getPassword().equals(password)) {
			i = 100;
			return i;
		}
		UserPayInfo userPayInfo = userPayInfoMapper.queryByUserId(userId);
		if (userPayInfo != null) {
			if (newPassword.equals(userPayInfo.getPwd())) {
				i = 200;
				return i;
			}
		}
		i = userMapper.updateUserPasswordById(userId, newPassword);
		return i;
	}

	/**
	 * 忘记密码息
	 * 
	 * @param Id
	 * @return
	 */
	@Override
	public int updateUserPasswordByUserName(String userName, String password, String code) {
		// TODO Auto-generated method stub
		int i;
		CheckCode checkCode = checkCodeMapper.selectCheckCodeByMobile(userName);
		if (!checkCode.getCode().equals(code)) {
			// 0验证码不正确
			i = 0;
			return i;
		}
		i = userMapper.updateUserPasswordByUserName(userName, password);
		// 1修改成功
		return i;
	}

	/**
	 * 退出登录
	 * 
	 * @param Id
	 * @return
	 */
	@Override
	public int updateUserLastLoginTime(long userId) {
		// TODO Auto-generated method stub
		int i = userMapper.updateUserLastLoginTime(userId);
		return i;
	}

	@Override
	public List<MyattentionTalent> selectPictureAndNickName(long userId, int page, int pageSize) {
		List<MyattentionTalent> myattentionTalentList = new ArrayList<MyattentionTalent>();
		// int total=userFansMapper.selectUserFansCount(userId);
		List<UserFans> userFansList = userFansMapper.selectUserFans(userId, page, pageSize);
		for (UserFans userFans : userFansList) {
			MyattentionTalent myattentionTalent = new MyattentionTalent();
			User user = userMapper.selectUserEntityById(userFans.getTalentId());
			myattentionTalent.setUserId(user.getId());
			myattentionTalent.setNickName(user.getNickName());
			myattentionTalent.setPicture(user.getPicture());
			myattentionTalentList.add(myattentionTalent);
		}
		return myattentionTalentList;
	}

	private void setUserToken(ResponseUser user, String clientType) throws Exception {
		user.setToken(tokenService.SaveToken(user, clientType));
		user.setPicture(user.getPicture());
		SdkHttpResult sdkHttpResult;
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("RONG_CLOUD_CREATE_TOKEN");
		if (null != baseRestrictions) {
			if (baseRestrictions.getStatus().toString().equals("0")) {// 禁用
				sdkHttpResult = new SdkHttpResult(200, "");// 返回空字符串
			} else {
				sdkHttpResult = ApiHttpClient.getToken(String.valueOf(user.getUserId()), user.getUserName(), user.getPicture(), FormatType.json);
			}
		} else {
			sdkHttpResult = ApiHttpClient.getToken(String.valueOf(user.getUserId()), user.getUserName(), user.getPicture(), FormatType.json);
		}
		user.setRongCloudToken(sdkHttpResult.getResult());
		// 缓存用户信息
		this.getUserById(user.getUserId());
		this.getUserByPersionId(user.getRecommendFrom());

	}

	@Override
	public ResponseEntity<?> updaterecommendUserRegister(String userName, String code, String recommendFrom, String nickName, String picture, int sex, String clientType) {
		CheckCode checkcode = checkCodeMapper.selectCheckCodeByMobile(userName);
		if (checkcode == null || !checkcode.getCode().equals(code)) {
			// 验证码不正确
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20109), HttpStatus.OK);
		}
		// 记录日志
		ChangeProcessLog ChangeLog = new ChangeProcessLog();
		ChangeLog.setMethod("UserServiceImpl.recommendUserRegister");
		ChangeLog.setTableName("yg_user.c_user");
		// TODO Auto-generated method stub
		UserInfo userInfoEntity = userInfoMapper.selectUserInfoByPersion(recommendFrom);
		User userEntity = userMapper.selectUserEntityById(userInfoEntity.getUserId());
		// 推荐人不是导师 、店主
		if (userEntity.getRoleId() != 7 && userEntity.getRoleId() != 6 && userEntity.getRoleId() != 5 && userEntity.getRoleId() != 4 && userEntity.getRoleId() != 3) {
			User user = userMapper.selectUserByUserName(userName);
			if (user != null) {
				// 用户已经注册
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20101), HttpStatus.OK);
			}
			/*
			 * // 查询最大身份id基数 int sign = userInfoMapper.selectUserinfoMaxSign(); if (sign <=
			 * 0) { sign = 100000; } sign += 1; // 随机两位大写字母拼接身份id基数 作为用户身份id String
			 * persionId = RandomUtil.getRandomStr(2) + sign;
			 */
			// 添加user表 手机号码 推荐人身份id 昵称 头像
			userMapper.insertUser(userName, "", recommendFrom, nickName, picture);
			// 添加成功之后查询一次用户
			ResponseUser user1 = userMapper.selectUserByUserNameNopassword2(userName);
			// 检查是否存在usermoney信息
			userMoneyService.checkExistUserMoney(user1.getUserId());
			// 添加userInfo 用户id 身份id基数 身份id基数 性别
			String persionId = UserUtil.getPersonId(user1.getUserId());
			userInfoMapper.insertUserInfo(user1.getUserId(), persionId, user1.getUserId().intValue(), sex);
			// 根据身份id查询用户信息
			UserInfo userInfo = userInfoMapper.selectUserInfoByPersion(persionId);
			// 经验值增加
			userMapper.updateUserEmpiricValue(userInfo.getUserId(), 10);
			// 记录日志
			ChangeLog.setPrimaryID(String.valueOf(userInfo.getUserId()));
			ChangeLog.getAfterMap().put("recommendFrom", recommendFrom);
			LogMapper.insert(ChangeLog);

			user1.setPersionId(userInfo.getPersionId());
			user1.setSex(userInfo.getSex());
			user1.setIsShow(0);
			/** 二维码推荐注册，不赠送礼包 */
			/*
			 * UserPromotion userPromotion = new UserPromotion(); Promotion promotion =
			 * promotionMapper.selectByPrimaryKey(25); List<PromotionDetail>
			 * listPromotionDetail =
			 * promotionDetailMapper.selectPromotionDetailByPromotionId(promotion.getId());
			 * for (PromotionDetail promotionDetail : listPromotionDetail) {
			 * userPromotion.setPromotionId(promotionDetail.getPromotionId());
			 * userPromotion.setPromotionDetailId(promotionDetail.getId());
			 * userPromotion.setType(promotionDetail.getType());
			 * userPromotion.setPromotionDetailName(promotionDetail.getPromotionDetailName()
			 * ); userPromotion.setUserId(user1.getUserId());
			 * userPromotion.setBrandId(promotionDetail.getBrandId());
			 * userPromotion.setGoodId(promotionDetail.getGoodId());
			 * userPromotion.setLimited(promotionDetail.getLimited());
			 * userPromotion.setIsDiscount(promotionDetail.getIsDiscount());
			 * userPromotion.setAmount(promotionDetail.getAmount());
			 * userPromotion.setEffectiveTime(promotionDetail.getEffectiveTime());
			 * userPromotion.setExpirationTime(promotionDetail.getExpirationTime());
			 * userPromotion.setPromotionNumber(1);
			 * userPromotion.setTargetSelfType(promotionDetail.getTargetSelfType());
			 * userPromotion.setDiscount(promotionDetail.getDiscount());
			 * userPromotionMapper.insertUserPromotion(userPromotion); }
			 */

			try {
				setUserToken(user1, clientType);
			} catch (Exception e) {
				// TODO: handle exception
			}

			logger.error("注册用户成功不等于3，4，5，6，7 ：角色ID: {} ", userEntity.getRoleId());
			return new ResponseEntity<>(new ResponseResultModel<ResponseUser>(user1), HttpStatus.OK);
		}

		// 推荐人关系是导师 讲师等级（1普通2会员3-6达人7讲师8网红9未知10未知）
		User user = userMapper.selectUserByUserName(userName);

		if (user == null) {
			logger.error("注册用户{}用户为空", userName);
		}
		logger.error("注册用户{}用户不为空", userName);
		if (user != null) {

			logger.error("注册用户角色ID {}", user.getRoleId());
			// 用户是普通身份
			if (user.getRoleId() == 1 || user.getRoleId() == 2 || user.getRoleId() == 8 || user.getRoleId() == 9 || user.getRoleId() == 10) {
				// 修改推荐人身份为达人导师身份id
				ChangeLog.setPrimaryID(String.valueOf(user.getId()));
				ChangeLog.getBeforeMap().put("recommendFrom", user.getRecommendFrom());
				ChangeLog.getAfterMap().put("recommendFrom", recommendFrom);
				userMapper.updateRecommendFromById(recommendFrom, user.getId());
				userMapper.updateUserEmpiricValue(user.getId(), 10);
				LogMapper.insert(ChangeLog);
				/** 二维码推荐注册，不赠送礼包 */
				/*
				 * // 绑定讲师<非校妆姐姐>时，校验是否已经赠送过56的礼包，没赠送的补送 if
				 * (!BaseConstants.XZ_SISTER_PERSION_ID.equals(recommendFrom)) {
				 * List<UserPromotion> userPromotion56List =
				 * userPromotionMapper.selectUserPromotionByPromotionIdAndUserId(56,
				 * user.getId()); // 没有56的礼包 if (CollectionUtils.isEmpty(userPromotion56List)) {
				 * UserPromotion userPromotion56 = new UserPromotion(); Promotion promotion56 =
				 * promotionMapper.selectByPrimaryKey(56); List<PromotionDetail>
				 * listPromotionDetail56 =
				 * promotionDetailMapper.selectPromotionDetailByPromotionId(promotion56.getId())
				 * ; for (PromotionDetail promotionDetail56 : listPromotionDetail56) {
				 * userPromotion56.setPromotionId(promotionDetail56.getPromotionId());
				 * userPromotion56.setPromotionDetailId(promotionDetail56.getId());
				 * userPromotion56.setType(promotionDetail56.getType());
				 * userPromotion56.setPromotionDetailName(promotionDetail56.
				 * getPromotionDetailName()); userPromotion56.setUserId(user.getId());
				 * userPromotion56.setBrandId(promotionDetail56.getBrandId());
				 * userPromotion56.setGoodId(promotionDetail56.getGoodId());
				 * userPromotion56.setLimited(promotionDetail56.getLimited());
				 * userPromotion56.setIsDiscount(promotionDetail56.getIsDiscount());
				 * userPromotion56.setAmount(promotionDetail56.getAmount());
				 * userPromotion56.setEffectiveTime(promotionDetail56.getEffectiveTime());
				 * userPromotion56.setExpirationTime(promotionDetail56.getExpirationTime());
				 * userPromotion56.setPromotionNumber(1);
				 * userPromotion56.setTargetSelfType(promotionDetail56.getTargetSelfType());
				 * userPromotion56.setDiscount(promotionDetail56.getDiscount());
				 * userPromotionMapper.insertUserPromotion(userPromotion56); } } }
				 */
				// 用户已经注册

				Map<String, Object> result = new HashMap<String, Object>();
				result.put("code", "20158");
				result.put("message", "该用户已注册，携手小铺店主：" + userEntity.getNickName());
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20101), HttpStatus.OK);
		}
		/*
		 * // 查询最大身份id基数 int sign = userInfoMapper.selectUserinfoMaxSign(); if (sign <=
		 * 0) { sign = 100000; } sign += 1; // 随机两位大写字母拼接身份id基数 作为用户身份id String
		 * persionId = RandomUtil.getRandomStr(2) + sign;
		 */
		// 添加user表 手机号码 推荐人身份id 昵称 头像
		userMapper.insertUserTalentTeacher(userName, "", recommendFrom, nickName, picture);
		// 添加成功之后查询一次用户
		ResponseUser user1 = userMapper.selectUserByUserNameNopassword2(userName);
		// 检查是否存在usermoney信息
		userMoneyService.checkExistUserMoney(user1.getUserId());
		// 添加userInfo 用户id 身份id基数 身份id基数 性别
		String persionId = UserUtil.getPersonId(user1.getUserId());
		userInfoMapper.insertUserInfo(user1.getUserId(), persionId, user1.getUserId().intValue(), sex);
		// 根据身份id查询用户信息
		UserInfo userInfo = userInfoMapper.selectUserInfoByPersion(persionId);
		// 经验值增加
		userMapper.updateUserEmpiricValue(userInfo.getUserId(), 10);
		// 记录日志
		ChangeLog.setPrimaryID(String.valueOf(userInfo.getUserId()));
		ChangeLog.getAfterMap().put("recommendFrom", recommendFrom);
		LogMapper.insert(ChangeLog);

		user1.setPersionId(userInfo.getPersionId());
		user1.setSex(userInfo.getSex());
		user1.setIsShow(1);
		/** 二维码推荐注册，不赠送礼包 */
		/*
		 * UserPromotion userPromotion1 = new UserPromotion(); Promotion promotion1 =
		 * promotionMapper.selectByPrimaryKey(25); List<PromotionDetail>
		 * listPromotionDetail1 =
		 * promotionDetailMapper.selectPromotionDetailByPromotionId(promotion1.getId());
		 * for (PromotionDetail promotionDetail1 : listPromotionDetail1) {
		 * userPromotion1.setPromotionId(promotionDetail1.getPromotionId());
		 * userPromotion1.setPromotionDetailId(promotionDetail1.getId());
		 * userPromotion1.setType(promotionDetail1.getType());
		 * userPromotion1.setPromotionDetailName(promotionDetail1.getPromotionDetailName
		 * ()); userPromotion1.setUserId(user1.getUserId());
		 * userPromotion1.setBrandId(promotionDetail1.getBrandId());
		 * userPromotion1.setGoodId(promotionDetail1.getGoodId());
		 * userPromotion1.setLimited(promotionDetail1.getLimited());
		 * userPromotion1.setIsDiscount(promotionDetail1.getIsDiscount());
		 * userPromotion1.setAmount(promotionDetail1.getAmount());
		 * userPromotion1.setEffectiveTime(promotionDetail1.getEffectiveTime());
		 * userPromotion1.setExpirationTime(promotionDetail1.getExpirationTime());
		 * userPromotion1.setPromotionNumber(1);
		 * userPromotion1.setTargetSelfType(promotionDetail1.getTargetSelfType());
		 * userPromotion1.setDiscount(promotionDetail1.getDiscount());
		 * userPromotionMapper.insertUserPromotion(userPromotion1); } UserPromotion
		 * userPromotion2 = new UserPromotion(); Promotion promotion2 =
		 * promotionMapper.selectByPrimaryKey(56); List<PromotionDetail>
		 * listPromotionDetail2 =
		 * promotionDetailMapper.selectPromotionDetailByPromotionId(promotion2.getId());
		 * for (PromotionDetail promotionDetail2 : listPromotionDetail2) {
		 * userPromotion2.setPromotionId(promotionDetail2.getPromotionId());
		 * userPromotion2.setPromotionDetailId(promotionDetail2.getId());
		 * userPromotion2.setType(promotionDetail2.getType());
		 * userPromotion2.setPromotionDetailName(promotionDetail2.getPromotionDetailName
		 * ()); userPromotion2.setUserId(user1.getUserId());
		 * userPromotion2.setBrandId(promotionDetail2.getBrandId());
		 * userPromotion2.setGoodId(promotionDetail2.getGoodId());
		 * userPromotion2.setLimited(promotionDetail2.getLimited());
		 * userPromotion2.setIsDiscount(promotionDetail2.getIsDiscount());
		 * userPromotion2.setAmount(promotionDetail2.getAmount());
		 * userPromotion2.setEffectiveTime(promotionDetail2.getEffectiveTime());
		 * userPromotion2.setExpirationTime(promotionDetail2.getExpirationTime());
		 * userPromotion2.setPromotionNumber(1);
		 * userPromotion2.setTargetSelfType(promotionDetail2.getTargetSelfType());
		 * userPromotion2.setDiscount(promotionDetail2.getDiscount());
		 * userPromotionMapper.insertUserPromotion(userPromotion2); }
		 */

		BaseRestrictions _baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("promotion_off");

		if (_baseRestrictions == null) {
			logger.error("开始赠送优惠券:  ============ 开关未配置,请检查缓存");
		}
		if (_baseRestrictions != null && _baseRestrictions.getExperience() == 1) {
			logger.error("开始赠送优惠券:  ============ 开关: {} , 推荐人ID： {} , 推荐人 ROLE_id : {} , 用户ID: {}, 用户手机: {}", _baseRestrictions.getExperience(), userEntity.getId(), userEntity.getRoleId(), user1.getUserId(), user1.getUserName());

			if (userEntity.getRoleId() == 4 || userEntity.getRoleId() == 3 || userEntity.getRoleId() == 7) {

				Long storeUserId = 0L;
				if (userEntity.getRoleId() == 7) {
					storeUserId = userEntity.getId();
				} else if (userEntity.getRoleId() == 4 || userEntity.getRoleId() == 3) {
					// selectUserRoleByPersonId
					ResponseUser _teacher = userMapper.selectUserRoleByPersonId(userEntity.getTalentTeacher());
					if (_teacher != null) {
						storeUserId = _teacher.getUserId();
					}
				}
				logger.error("开始赠送优惠券:  用户ID：{} ,讲师ID：{}", user1.getUserId(), storeUserId);
				Integer expirationDay = this.baseRestrictionsService.getBaseRestrictionsForCache("expiration_day").getExperience();
				String jobNo = "0";
				TalentJob talentJob = talentJobMapper.selectTalentJobByUserId(userEntity.getId());
				if (talentJob != null) {
					jobNo = talentJob.getJobNo();
				}
				Date nowDate = DateUtil.toDate(System.currentTimeMillis());
				// 优惠券礼包赠送主表
				GivePromotionList givePromotionList = new GivePromotionList();
				givePromotionList.setTearchUserId(storeUserId.intValue());
				givePromotionList.setTearchJobNo(jobNo);
				givePromotionList.setGiveTime(nowDate);
				givePromotionList.setPromotionId(25);
				givePromotionList.setAdminUserId(0);
				givePromotionList.setNums(1);
				// this.givePromotionListMapper.insertAndGetId(givePromotionList);
				GivePromotionHistory gph = new GivePromotionHistory();
				gph.setTearchUserId(Long.valueOf(storeUserId));
				gph.setTearchJobNo(jobNo);
				gph.setAdminUserId(0L);
				gph.setUserId(user1.getUserId());
				gph.setUserRoleId(Long.valueOf(user1.getRoleId()));
				gph.setPromotionId(25L);
				gph.setGiveTime(nowDate);
				gph.setExpirationTime(DateUtil.parse(DateUtil.getFewDays(expirationDay)));
				gph.setStatus(1);
				gph.setpId(givePromotionList.getId());
				// this.givePromotionHistoryMapper.insertSelective(gph);

			}

		}

		try {
			setUserToken(user1, clientType);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return new ResponseEntity<>(new ResponseResultModel<ResponseUser>(user1), HttpStatus.OK);
	}

	@Override
	public ResponseEntity<?> webpageRegister(String userName, String code, String recommendFrom, String clientType) {
		// TODO Auto-generated method stub
		// 记录用户信息变化 日志
		ChangeProcessLog ChangeLog = new ChangeProcessLog();
		ChangeLog.setMethod("UserServiceImpl.webpageRegister");
		ChangeLog.setTableName("yg_user.c_user");
		UserInfo userInfoEntity = userInfoMapper.selectUserInfoByPersion(recommendFrom);
		User userEntity = userMapper.selectUserEntityById(userInfoEntity.getUserId());
		// 推荐人不是导师
		if (userEntity.getRoleId() != 7 && userEntity.getRoleId() != 6 && userEntity.getRoleId() != 5 && userEntity.getRoleId() != 4 && userEntity.getRoleId() != 3) {
			User user = userMapper.selectUserByUserName(userName);
			if (user != null) {
				// 用户已经注册
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20101), HttpStatus.OK);
			}
			CheckCode checkcode = checkCodeMapper.selectCheckCodeByMobile(userName);
			if (!checkcode.getCode().equals(code)) {
				// 验证码不正确
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20109), HttpStatus.OK);
			}
			// 查询最大身份id基数
			/*
			 * int sign = userInfoMapper.selectUserinfoMaxSign(); if (sign <= 0) { sign =
			 * 100000; } sign += 1; // 随机两位大写字母拼接身份id基数 作为用户身份id String persionId =
			 * RandomUtil.getRandomStr(2) + sign;
			 */
			// 添加user表 手机号码 推荐人身份id 昵称 头像
			userMapper.insertUser(userName, "", recommendFrom, "", "");
			// 添加成功之后查询一次用户
			ResponseUser user1 = userMapper.selectUserByUserNameNopassword2(userName);
			// 检查是否存在usermoney信息
			userMoneyService.checkExistUserMoney(user1.getUserId());
			// 添加userInfo 用户id 身份id基数 身份id基数 性别
			String persionId = UserUtil.getPersonId(user1.getUserId());
			userInfoMapper.insertUserInfo(user1.getUserId(), persionId, user1.getUserId().intValue(), 1);
			// 根据身份id查询用户信息
			UserInfo userInfo = userInfoMapper.selectUserInfoByPersion(persionId);

			// 经验值增加
			userMapper.updateUserEmpiricValue(userInfo.getUserId(), 10);
			// 记录日志
			ChangeLog.setPrimaryID(String.valueOf(userInfo.getUserId()));
			ChangeLog.getAfterMap().put("recommendFrom", recommendFrom);
			user1.setPersionId(userInfo.getPersionId());
			user1.setSex(userInfo.getSex());
			user1.setIsShow(0);
			/** 二维码推荐注册，不赠送礼包 */
			/*
			 * UserPromotion userPromotion = new UserPromotion(); Promotion promotion =
			 * promotionMapper.selectByPrimaryKey(25); List<PromotionDetail>
			 * listPromotionDetail = promotionDetailMapper
			 * .selectPromotionDetailByPromotionId(promotion.getId()); for (PromotionDetail
			 * promotionDetail : listPromotionDetail) {
			 * userPromotion.setPromotionId(promotionDetail.getPromotionId());
			 * userPromotion.setPromotionDetailId(promotionDetail.getId());
			 * userPromotion.setType(promotionDetail.getType());
			 * userPromotion.setPromotionDetailName(promotionDetail
			 * .getPromotionDetailName()); userPromotion.setUserId(user1.getUserId());
			 * userPromotion.setBrandId(promotionDetail.getBrandId());
			 * userPromotion.setGoodId(promotionDetail.getGoodId());
			 * userPromotion.setLimited(promotionDetail.getLimited());
			 * userPromotion.setIsDiscount(promotionDetail.getIsDiscount());
			 * userPromotion.setAmount(promotionDetail.getAmount());
			 * userPromotion.setEffectiveTime(promotionDetail .getEffectiveTime());
			 * userPromotion.setExpirationTime(promotionDetail .getExpirationTime());
			 * userPromotion.setPromotionNumber(1);
			 * userPromotion.setTargetSelfType(promotionDetail.getTargetSelfType());
			 * userPromotion.setDiscount(promotionDetail.getDiscount());
			 * userPromotionMapper.insertUserPromotion(userPromotion); }
			 */
			// 保存日志
			LogMapper.insert(ChangeLog);
			try {
				setUserToken(user1, clientType);
			} catch (Exception e) {
				// TODO: handle exception
			}
			return new ResponseEntity<>(new ResponseResultModel<ResponseUser>(user1), HttpStatus.OK);
		}

		// 推荐人关系是导师 店主
		User user = userMapper.selectUserByUserName(userName);
		if (user != null) {
			// 用户是普通身份
			if (user.getRoleId() == 1 || user.getRoleId() == 2 || user.getRoleId() == 8 || user.getRoleId() == 9 || user.getRoleId() == 10) {
				// 修改推荐人身份为达人导师身份id
				ChangeLog.setPrimaryID(String.valueOf(user.getId()));
				ChangeLog.getBeforeMap().put("recommendFrom", user.getRecommendFrom());
				ChangeLog.getAfterMap().put("recommendFrom", recommendFrom);
				userMapper.updateRecommendFromById(recommendFrom, user.getId());
				userMapper.updateUserEmpiricValue(user.getId(), 10);
				// 保存日志
				LogMapper.insert(ChangeLog);
				// 用户已经注册
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20158), HttpStatus.OK);
			}
			if (user.getRoleId() != 1 || user.getRoleId() != 2 || user.getRoleId() != 8 || user.getRoleId() != 9 || user.getRoleId() != 10) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20101), HttpStatus.OK);
			}
		}
		CheckCode checkcode = checkCodeMapper.selectCheckCodeByMobile(userName);
		if (!checkcode.getCode().equals(code)) {
			// 验证码不正确
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20109), HttpStatus.OK);
		}
		// 查询最大身份id基数
		/*
		 * int sign = userInfoMapper.selectUserinfoMaxSign(); if (sign <= 0) { sign =
		 * 100000; } sign += 1; // 随机两位大写字母拼接身份id基数 作为用户身份id String persionId =
		 * RandomUtil.getRandomStr(2) + sign;
		 */
		// 添加user表 手机号码 推荐人身份id 昵称 头像
		userMapper.insertUserTalentTeacher(userName, "", recommendFrom, "", "");
		// 添加成功之后查询一次用户
		ResponseUser user1 = userMapper.selectUserByUserNameNopassword2(userName);
		// 检查是否存在usermoney信息
		userMoneyService.checkExistUserMoney(user1.getUserId());
		// 添加userInfo 用户id 身份id基数 身份id基数 性别
		String persionId = UserUtil.getPersonId(user1.getUserId());
		userInfoMapper.insertUserInfo(user1.getUserId(), persionId, user1.getUserId().intValue(), 1);
		// 根据身份id查询用户信息
		UserInfo userInfo = userInfoMapper.selectUserInfoByPersion(persionId);
		// 经验值增加
		userMapper.updateUserEmpiricValue(userInfo.getUserId(), 10);
		// 记录日志
		ChangeLog.setPrimaryID(String.valueOf(userInfo.getUserId()));
		ChangeLog.getAfterMap().put("recommendFrom", recommendFrom);
		// 保存日志
		LogMapper.insert(ChangeLog);
		user1.setPersionId(userInfo.getPersionId());
		user1.setSex(userInfo.getSex());
		user1.setIsShow(1);
		/** 二维码推荐注册，不赠送礼包 */
		/*
		 * UserPromotion userPromotion = new UserPromotion(); Promotion promotion =
		 * promotionMapper.selectByPrimaryKey(25); List<PromotionDetail>
		 * listPromotionDetail = promotionDetailMapper
		 * .selectPromotionDetailByPromotionId(promotion.getId()); for (PromotionDetail
		 * promotionDetail : listPromotionDetail) {
		 * userPromotion.setPromotionId(promotionDetail.getPromotionId());
		 * userPromotion.setPromotionDetailId(promotionDetail.getId());
		 * userPromotion.setType(promotionDetail.getType());
		 * userPromotion.setPromotionDetailName(promotionDetail
		 * .getPromotionDetailName()); userPromotion.setUserId(user1.getUserId());
		 * userPromotion.setBrandId(promotionDetail.getBrandId());
		 * userPromotion.setGoodId(promotionDetail.getGoodId());
		 * userPromotion.setLimited(promotionDetail.getLimited());
		 * userPromotion.setIsDiscount(promotionDetail.getIsDiscount());
		 * userPromotion.setAmount(promotionDetail.getAmount());
		 * userPromotion.setEffectiveTime(promotionDetail.getEffectiveTime());
		 * userPromotion .setExpirationTime(promotionDetail.getExpirationTime());
		 * userPromotion.setPromotionNumber(1);
		 * userPromotion.setTargetSelfType(promotionDetail.getTargetSelfType());
		 * userPromotion.setDiscount(promotionDetail.getDiscount());
		 * userPromotionMapper.insertUserPromotion(userPromotion); }
		 */
		try {
			setUserToken(user1, clientType);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return new ResponseEntity<>(new ResponseResultModel<ResponseUser>(user1), HttpStatus.OK);
	}

	@Override
	public List<MyattentionTalent> selectUserByRecommendFrom(String recommendFrom, int page, int pageSize) {
		// TODO Auto-generated method stub
		List<MyattentionTalent> myattentionTalentList = new ArrayList<MyattentionTalent>();
		List<User> userList = userMapper.selectUserByRecommendFrom(recommendFrom, page, pageSize);
		for (User user : userList) {
			MyattentionTalent myattentionTalent = new MyattentionTalent();
			User user1 = userMapper.selectUserEntityById(user.getId());
			myattentionTalent.setUserId(user.getId());
			myattentionTalent.setNickName(user1.getNickName());
			myattentionTalent.setUserName(user1.getUserName());
			myattentionTalent.setPicture(user1.getPicture());
			myattentionTalent.setBindRecommendMode(user1.getBindRecommendMode());
			myattentionTalent.setCreateTime(null == user1.getLastBindTime() ? "" : user1.getLastBindTime().substring(0, 19));
			myattentionTalentList.add(myattentionTalent);
		}
		return myattentionTalentList;
	}

	@Override
	public MyInvitationFriend selectUserByRecommendFromCount(String recommendFrom) {
		// TODO Auto-generated method stub
		MyInvitationFriend myInvitationFriend = new MyInvitationFriend();
		int recommendQuantity = userMapper.selectUserByRecommendFromCount(recommendFrom);
		myInvitationFriend.setRecommendQuantity(recommendQuantity);
		myInvitationFriend.setEmpiricValue(recommendQuantity * 10);
		return myInvitationFriend;
	}

	@Override
	public int updateNickName(String nickName, long id) {
		// TODO Auto-generated method stub
		int i = userMapper.updateUserNickName(nickName, id);
		return i;
	}

	@Override
	public int updateUserPicture(String picture, long id) {
		// TODO Auto-generated method stub
		int i = userMapper.updateUserPicture(picture, id);
		return i;
	}

	@Override
	public ResponseUser dynamicRegister(String userName) {
		ResponseUser user = userMapper.selectUserByUserNameNopassword2(userName);
		if (user == null) {
			/*
			 * int sign = userInfoMapper.selectUserinfoMaxSign(); if (sign <= 0) { sign =
			 * 100000; } sign += 1; String persionId = RandomUtil.getRandomStr(2) + sign;
			 */
			String recommendFrom = "";
			// 校妆姐姐店铺的店主ID
			Integer storeUserId = Integer.valueOf(BaseConstants.XZ_SISTER + "");
			// 默认普通推荐人身份为校妆姐姐
			if (storeUserId != null) {
				UserInfo xzjjUserInfo = userInfoMapper.selectByUserId(Long.valueOf(storeUserId));
				if (xzjjUserInfo != null) {
					recommendFrom = xzjjUserInfo.getPersionId();
				}
			}
			// 保存用户
			userMapper.insertUser(userName, "", recommendFrom, "", "");

			// 开始记录日志
			ChangeProcessLog Log = new ChangeProcessLog();
			Log.setDescription("用户注册");
			Log.setMethod("UserServiceImpl.dynamicRegister");
			Log.setPrimaryID("");
			Log.setTableName("yg_user.c_user");
			Log.getAfterMap().put("recommendFrom", recommendFrom);
			LogMapper.insert(Log);

			User user1 = userMapper.selectUserByUserName(userName);
			// 检查是否存在usermoney信息
			userMoneyService.checkExistUserMoney(user1.getId());
			userInfoMapper.insertUserInfo(user1.getId(), UserUtil.getPersonId(user1.getId()), user1.getId().intValue(), 0);
			/** 验证码注册：默认绑定校妆姐姐，自动送礼包 */
			/*
			 * UserPromotion userPromotion = new UserPromotion(); Promotion promotion =
			 * promotionMapper.selectByPrimaryKey(25); List<PromotionDetail>
			 * listPromotionDetail =
			 * promotionDetailMapper.selectPromotionDetailByPromotionId(promotion.getId());
			 * for (PromotionDetail promotionDetail : listPromotionDetail) {
			 * userPromotion.setPromotionId(promotionDetail.getPromotionId());
			 * userPromotion.setPromotionDetailId(promotionDetail.getId());
			 * userPromotion.setType(promotionDetail.getType());
			 * userPromotion.setPromotionDetailName(promotionDetail.getPromotionDetailName()
			 * ); userPromotion.setUserId(user1.getId());
			 * userPromotion.setBrandId(promotionDetail.getBrandId());
			 * userPromotion.setGoodId(promotionDetail.getGoodId());
			 * userPromotion.setLimited(promotionDetail.getLimited());
			 * userPromotion.setIsDiscount(promotionDetail.getIsDiscount());
			 * userPromotion.setAmount(promotionDetail.getAmount());
			 * userPromotion.setEffectiveTime(promotionDetail.getEffectiveTime());
			 * userPromotion.setExpirationTime(promotionDetail.getExpirationTime());
			 * userPromotion.setPromotionNumber(1);
			 * userPromotion.setTargetSelfType(promotionDetail.getTargetSelfType());
			 * userPromotion.setDiscount(promotionDetail.getDiscount());
			 * userPromotionMapper.insertUserPromotion(userPromotion); }
			 */
			// 优惠券过期时间
			Integer expirationDay = this.baseRestrictionsService.getBaseRestrictionsForCache("expiration_day").getExperience();
			String jobNo = "0";
			TalentJob talentJob = talentJobMapper.selectTalentJobByUserId(user1.getId());
			if (talentJob != null) {
				jobNo = talentJob.getJobNo();
			}
			Date nowDate = DateUtil.toDate(System.currentTimeMillis());
			// 优惠券礼包赠送主表
			GivePromotionList givePromotionList = new GivePromotionList();
			givePromotionList.setTearchUserId(storeUserId);
			givePromotionList.setTearchJobNo(jobNo);
			givePromotionList.setGiveTime(nowDate);
			givePromotionList.setPromotionId(25);
			givePromotionList.setAdminUserId(0);
			givePromotionList.setNums(1);
			// this.givePromotionListMapper.insertAndGetId(givePromotionList);
			GivePromotionHistory gph = new GivePromotionHistory();
			gph.setTearchUserId(Long.valueOf(storeUserId));
			gph.setTearchJobNo(jobNo);
			gph.setAdminUserId(0L);
			gph.setUserId(user1.getId());
			gph.setUserRoleId(Long.valueOf(user1.getRoleId()));
			gph.setPromotionId(25L);
			gph.setGiveTime(nowDate);
			gph.setExpirationTime(DateUtil.parse(DateUtil.getFewDays(expirationDay)));
			gph.setStatus(1);
			gph.setpId(givePromotionList.getId());
			// this.givePromotionHistoryMapper.insertSelective(gph);

			ResponseUser user2 = userMapper.selectUserByUserNameNopassword2(userName);
			UserInfo userinfo = userInfoMapper.selectByUserId(user2.getUserId());
			user2.setPersionId(userinfo.getPersionId());
			user2.setSex(userinfo.getSex());
			// TODO Auto-generated method stub
			return user2;
		}
		UserInfo userinfo = userInfoMapper.selectByUserId(user.getUserId());
		user.setPersionId(userinfo.getPersionId());
		user.setSex(userinfo.getSex());
		// TODO Auto-generated method stub
		return user;

	}

	/**
	 * 美妆咨询界面
	 * 
	 * @author 卫耀华
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<ResponseUserVo> selectUserByRoleId7NoPassword(int pageLimit, int pageSize) {
		List<ResponseUserVo> voList = new ArrayList<ResponseUserVo>();
		List<User> list = userMapper.selectUserByRoleId7NoPassword(pageLimit, pageSize);
		if (list != null && list.size() > 0) {
			for (User user : list) {
				ResponseUserVo ru = new ResponseUserVo();
				BeanUtils.copyProperties(user, ru);
				ru.setUserId(user.getId());
				voList.add(ru);
			}
		}
		return voList;
	}

	/**
	 * 美妆咨询界面
	 * 
	 * @author 卫耀华
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public int countUserByRoleId7() {
		return userMapper.countUserByRoleId7();
	}

	/**
	 * 我邀请的好友数
	 * 
	 * @author 卫耀华
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public int selectInvitationNumByUserId(Long userId) {
		UserInfo info = userInfoMapper.selectByUserId(userId);
		return userMapper.selectUserByRecommendFromCount(info.getPersionId());
	}

	@Override
	public int selectUserMoney(Long userId) {
		return userMapper.selectUserMoney(userId);
	}

	/**
	 * 用户是否关注此达人
	 * 
	 * @author 卫耀华
	 */
	@Override
	public int userIsEnjoyThisTalent(Long talentId, Long userId) {
		if (userId > 0) {
			int n = userFansMapper.selectUserFansByUserIdAndTalentID(talentId, userId);
			if (n > 0) {
				return BizConstant.ENJOY_TYPE_Y;// 是否关注了这个达人,Y或N回复
			}
		}
		return BizConstant.ENJOY_TYPE_N;
	}

	/**
	 * 达人主页邀请修改大人主页的背景图和达人简介
	 * 
	 * @author 卫耀华
	 * @param talentId
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int updateUserJianjieAndBackgroundImageById(Long talentId, String talentDescription, String talentBackgroundImage) {
		return userMapper.updateUserSynopsisAndBackgroundImageById(talentId, talentDescription, talentBackgroundImage);
	}

	@Override
	public int updateSubMoneyById(long id, long cashCoin) {
		return userMapper.subMoneyById(id, cashCoin);
	}

	@Override
	public ResponseUser selectUserRoleById(long userId) {
		return userMapper.selectUserRoleById(userId);
	}

	@Override
	public ResponseUser selectUserRoleByPersonId(String personId) {
		return userMapper.selectUserRoleByPersonId(personId);
	}

	@Override
	public List<CRole> selectRoleByRoleType(Integer roleType) {
		return cRoleMapper.selectByRoleType(roleType);
	}

	@Override
	public List<CRole> selectRoleByRoleTypeNot(Integer roleType) {
		return cRoleMapper.selectByRoleTypeNot(roleType);
	}

	/*
	 * public int batchMemberRecommendById(List<User> list) { return
	 * userMapper.batchMemberRecommendById(list); }
	 */

	@Override
	public MemberFeeAndTotalSale selectMemberFeeAndTotalSale(long userId) {
		// TODO Auto-generated method stub
		MemberFeeAndTotalSale memberFeeAndTotalSale = new MemberFeeAndTotalSale();
		// User user = userMapper.selectUserEntityByIdNoPassword(userId);
		memberFeeAndTotalSale.setMoney(6000);// 88
		memberFeeAndTotalSale.setTotalSale(userMapper.selectOrderDetailByUserIdSumTotalFee(userId));
		int i = 19900 - userMapper.selectOrderDetailByUserIdSumTotalFee(userId);
		if (i <= 0) {
			i = 0;
		}
		memberFeeAndTotalSale.setDifferPrice(i);
		// 调用成为会员接口 看我代码
		return memberFeeAndTotalSale;
	}

	/*
	 * @Override public int updateUpMemberInId(List<User> userList) { return
	 * userMapper.updateUpMemberInId(userList); }
	 */

	@Override
	public List<User> selectUserWhereUserNameIsNull() {
		return userMapper.selectUserWhereUserNameIsNull();
	}

	/*
	 * @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public
	 * void cancelTalentQualification(List<User> userList) { for (User user :
	 * userList) { userMapper.deleteUserById(user.getId());
	 * userInfoMapper.deleteUserInfoByUserId(user.getId()); } }
	 */

	@Override
	public int batchUpdateMoney(List<UserJournal> list) {
		return userMapper.batchUpdateMoney(list);
	}

	@Override
	public UserInfo selectUserInfoByUserId(long userId) {
		return userInfoMapper.selectUserInfoByUserId(userId);
	}

	/**
	 * 校妆网~根据某用户的推荐人身份ID查询推荐人信息
	 * 
	 * @author 卫耀华
	 * @param persionId
	 * @return
	 */
	@Override
	public UserInfo selectUserInfoByPersionId(String persionId) {
		return userInfoMapper.selectUserInfoByPersionId(persionId);
	}

	@Override
	public int updateisOpenRecommandById(int isOpenRecommand, long id) {
		// TODO Auto-generated method stub
		int a = 0;
		if (isOpenRecommand == 2) {
			a = 0;
		} else {
			a = 1;
		}
		return userMapper.updateisOpenRecommandById(a, id);
	}

	/**
	 * 
	 * 方法用途：用于判断该用户是否购买过B区自营商品，且存在过【单笔订单】金额满360元且支付成功的记录，返回结果大于0，就满足，否则不满足
	 * 
	 * @author 卫耀华
	 * @date 2017-02-20
	 * @param userId
	 * @return
	 */
	@Override
	public int countSingleOrderInfo(long userId) {
		Integer num = userMapper.countSingleOrderInfo(userId);
		if (num != null) {
			// 如果查询结果不为空，就是满足换头像条件的
			return num.intValue();
		}
		return 0;
	}

	@Override
	public int updateOpenStoreInfoById(long id, String recommendFrom, String talentTeacher) {
		// TODO Auto-generated method stub
		return userMapper.updateOpenStoreInfoById(id, recommendFrom, talentTeacher);
	}

	@Override
	public UserInfo selectByUserId(Long userId) {
		// TODO Auto-generated method stub
		return userInfoMapper.selectByUserId(userId);
	}

	/**
	 * 用户是否关注此达人
	 * 
	 * @author 卫耀华
	 * @param userId
	 * @param talentId
	 * @return
	 */
	@Override
	public int userIsEnjoyTalent(long userId, long talentId) {
		if (userId > 0L) {
			int isFans = userFansMapper.selectUserFansByUserIdAndTalentID(talentId, userId);
			if (isFans > 0) {
				return BizConstant.ENJOY_TYPE_Y;
			}
		}
		return BizConstant.ENJOY_TYPE_N;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void selectUserInsert() {
		List<Integer> userIdList = userMapper.selectUserInsert();
		for (Integer userId : userIdList) {
			// 检查是否存在usermoney信息
			userMoneyService.checkExistUserMoney(userId);
			/*
			 * int sign = userInfoMapper.selectUserinfoMaxSign(); if (sign <= 0) { sign =
			 * 100000; } sign += 1; String persionId = RandomUtil.getRandomStr(2) + sign;
			 */

			userInfoMapper.insertUserInfo(userId, UserUtil.getPersonId(Long.valueOf(userId + "")), userId, 0);
		}

	}

	/**
	 * 校妆四期讲师搜索
	 */
	@Override
	public List<ResponseTeacher> searchTeacher(int startIndex, int pageSize, String searchText) {
		// TODO Auto-generated method stub
		List<ResponseTeacher> resModel = new ArrayList<ResponseTeacher>();
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(searchText);
		if (isNum.matches() && searchText.length() == 11) {
			resModel = userMapper.selectTeacherByPhone(searchText);
		} else {
			resModel = userMapper.selectTeacherByLikeNickName("%" + searchText + "%", startIndex, pageSize);
		}
		return resModel;
	}

	@Override
	public ResponseEntity<?> getUserTeacherInfo(long userId) {
		// TODO Auto-generated method stub
		User user = userMapper.selectUserEntityById(userId);
		if (user == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
		}
		UserInfo userInfo = userInfoMapper.selectUserInfoByPersion(user.getTalentTeacher());
		if (userInfo == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
		}
		User teacher = userMapper.selectUserEntityById(userInfo.getUserId());
		if (teacher == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20412), HttpStatus.OK);
		}
		if (teacher.getRoleId() != 7) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20411), HttpStatus.OK);
		}
		ReponseUserTeacher reponseUserTeacher = new ReponseUserTeacher();
		reponseUserTeacher.setNickName(teacher.getNickName());
		reponseUserTeacher.setUserName(teacher.getUserName());
		reponseUserTeacher.setPicture(teacher.getPicture());
		reponseUserTeacher.setUserId(teacher.getId());
		return new ResponseEntity<>(new ResponseResultModel<ReponseUserTeacher>(reponseUserTeacher), HttpStatus.OK);
	}

	@Override
	public void calculateUserRole(long userId, int roleId) {
		// try {
		// QueueRedisUtil.publish(new QueueUserSetRoleVo(userId, roleId));
		// } catch (Exception e) {
		// logger.error("发送计算用户角色消息失败：{}", e.getMessage(), e);
		// }
	}

	@Override
	public User selectUserForTearch(String jobNo) {
		TalentJob talentJob = talentJobMapper.selectTalentJobByJobNo(jobNo);
		return userMapper.selectByPrimaryKey(talentJob.getUserId());
	}

	@Override
	public String getXzSisterPersion() {
		return BaseConstants.XZ_SISTER_PERSION_ID;
		// BaseRestrictions _xz_sister =
		// baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.XZ_SISTER);
		// if (_xz_sister == null) {
		// return "GZ106163";
		// } else {
		// UserInfo selectByUserId = selectByUserId(_xz_sister.getExperience() + 0l);
		// if (selectByUserId == null) {
		// return "GZ106163";
		// } else {
		// return selectByUserId.getPersionId();
		// }
		// }
	}

	@Override
	public int resetUserPasswordByUserId(Long id, String password) {
		int i = 0;
		User user = userMapper.selectUserEntityById(id);
		if (null == user) {
			return i;
		}
		return userMapper.updateUserPasswordById(id, password);
	}

	@Override
	public int updateUserLoginInfo(User user) {
		return userMapper.updateByLogin(user);
	}

	@Override
	public void updateUserCacheByUserId(Long userId) {
		User _cacheUser = userMapper.selectByPrimaryKey(userId);
		if (_cacheUser != null) {
			String _key = RedisKey.USER_INFO_KEY_HASH + userId;
			redisUtil.hmset(_key, _cacheUser);
		}
	}

	@Override
	public void updateUserCacheByUserName(String userName) {
		User _cacheUser = userMapper.getUserByName(userName);
		if (_cacheUser != null) {
			String _key = RedisKey.USER_INFO_KEY_HASH + _cacheUser.getId();
			redisUtil.hmset(_key, _cacheUser);
		}
	}

	@Override
	public void cacheUserPersionByUserId(Long userId) {
		// User _cacheUser = userMapper.selectByPrimaryKey(userId);
		UserInfo _userInfo = userInfoMapper.selectByUserId(userId);
		if (_userInfo != null) {
			String _key = RedisKey.USER_INFO_KEY_STRING + _userInfo.getPersionId();
			redisUtil.set(_key, _userInfo.getUserId());
		}

	}

	@Override
	public void cacheUserPersionByUserByUserName(String userName) {

		User _cacheUser = userMapper.getUserByName(userName);

		if (_cacheUser != null) {
			UserInfo _userInfo = userInfoMapper.selectByUserId(_cacheUser.getId());
			if (_userInfo != null) {
				String _key = RedisKey.USER_INFO_KEY_STRING + _userInfo.getPersionId();
				redisUtil.set(_key, _userInfo.getUserId());
			}
		}
	}

	@Override
	public List<User> selectUserByUpdateTime(String updateTime) {
		return userMapper.selectUserByUpdateTime(updateTime);
	}

	@Override
	public User getUserById(Long userId) {

		String _key = RedisKey.USER_INFO_KEY_HASH + userId;

		User u = redisUtil.hmgetToObject(_key, User.class);
		if (u == null) {
			u = userMapper.selectByPrimaryKey(userId);
			updateUserCacheByUserId(userId);
		}
		return u;
	}

	@Override
	public User getUserByPersionId(String persionId) {
		String _key = RedisKey.USER_INFO_KEY_STRING + persionId;
		String userId = redisUtil.get(_key);

		if (StringUtils.isBlank(userId)) {
			User _u = userMapper.selectRecommendFromByPersionId(persionId);
			if (_u != null) {
				this.cacheUserPersionByUserId(Long.valueOf(_u.getId()));
			}
			return _u;
		}
		return getUserById(Long.valueOf(userId));
	}

	@Override
	public List<Long> getUserRoleEnum(long[] roleIds) {
		String string = redisUtil.get(RedisKeys.ROLE_IDS);
		List<Long> parseArray = JSONArray.parseArray(string, Long.class);
		if (CollectionUtils.isEmpty(parseArray)) {
			parseArray = userMapper.selectUserRoleEnum(roleIds);
			redisUtil.setex(RedisKeys.ROLE_IDS, 3600, JSONArray.toJSONString(parseArray));
		}
		return parseArray;
	}

	@Override
	public ResponseUser getStoreUserByUserId(long userId) {
		User selectByPrimaryKey = userMapper.selectByPrimaryKey(userId);
		if (selectByPrimaryKey == null) {
			return null;
		}
		return userMapper.selectUserRoleByPersonId(selectByPrimaryKey.getRecommendFrom());
	}

	@Override
	public void cacheUserInfoByUserId(Long userId) {
		UserInfo _cacheUserInfo = userInfoMapper.selectByUserId(userId);
		if (_cacheUserInfo != null) {
			String _key = RedisKey.C_USER_INFO_KEY_HASH + userId;
			redisUtil.hmset(_key, _cacheUserInfo);
		}
	}

	@Override
	public UserInfo selectUserInfoFormCacheByUserId(Long userId) {
		String _key = RedisKey.C_USER_INFO_KEY_HASH + userId;
		UserInfo _cacheUserInfo = redisUtil.hmgetToObject(_key, UserInfo.class);
		if (_cacheUserInfo == null) {
			_cacheUserInfo = userInfoMapper.selectByUserId(userId);
			if (_cacheUserInfo != null)
				redisUtil.hmset(_key, _cacheUserInfo);
		}
		return _cacheUserInfo;
	}

	@Override
	public CRole selectCRoleFormCacheByUserId(Integer roleId) {

		String _key = RedisKey.C_ROLE_KEY_HASH + roleId;

		CRole _cacheRole = redisUtil.hmgetToObject(_key, CRole.class);

		if (_cacheRole == null) {
			_cacheRole = cRoleMapper.selectByPrimaryKey(roleId);
			if (_cacheRole != null)
				redisUtil.hmset(_key, _cacheRole);

		}

		return _cacheRole;
	}

	@Override
	public void cacheUserRoleInfo() {
		List<CRole> roleList = cRoleMapper.selectByRoleTypeNot(1000);
		String _key = null;
		for (CRole _role : roleList) {
			if (_role != null) {
				_key = RedisKey.C_ROLE_KEY_HASH + _role.getId();
				redisUtil.hmset(_key, _role);
			}
		}
	}

	@Override
	public ResponseUser selectUserRoleFormCacheById(long userId) {
		ResponseUser _respUser = new ResponseUser();

		User _u = getUserById(userId);

		if (_u != null) {
			CRole _role = selectCRoleFormCacheByUserId(_u.getRoleId());
			UserInfo _info = selectUserInfoFormCacheByUserId(_u.getId());
			_respUser.setRecommendFrom(_u.getRecommendFrom());
			_respUser.setRoleId(_u.getRoleId());
			_respUser.setPassword(_u.getPassword());
			_respUser.setUserName(_u.getUserName());
			_respUser.setNickName(_u.getNickName());
			_respUser.setUserId(_u.getId());
			_respUser.setLockStatus(_u.getLockStatus());
			_respUser.setIsBlack(_u.getIsBlack());
			_respUser.setIsStore(_u.getIsStore());
			_respUser.setStoreId(_u.getStoreId());
			_respUser.setMoney(0L);
			_respUser.setSynopsis(_u.getSynopsis());
			_respUser.setTalentEffectTime(_u.getTalentEffectTime());
			_respUser.setTalentFailureTime(_u.getTalentFailureTime());
			_respUser.setEmpiricValue(_u.getEmpiricValue());
			_respUser.setPicture(_u.getPicture());
			_respUser.setRealName(_u.getNickName());

			_respUser.setFansCount(_u.getFansCount());
			_respUser.setIsHasLoginPwd("no");
			if (StringUtils.isNotBlank(_u.getPassword())) {
				_respUser.setIsHasLoginPwd("yes");
			}

			_respUser.setUserMachineCode(_u.getUserMachineCode());
			_respUser.setIsOpenRecommand(_u.getIsOpenRecommand());
			_respUser.setTotalSale(0);

			_respUser.setPersionId(_info.getPersionId());
			_respUser.setBindType(_info.getBindType());
			_respUser.setMemberRecommend(_u.getMemberRecommend());
			_respUser.setTalentTeacher(_u.getTalentTeacher());
			_respUser.setBackgroundImage(_u.getBackgroundImage());
			_respUser.setRongCloudToken(_u.getRongCloudToken());
			_respUser.setToken("TOKEN 请调用其它方法进行获取需要CLIENT_TYPE");
			_respUser.setLevel(_role.getLevel());
			_respUser.setRoleCode(_role.getRoleCode());
			_respUser.setRoleName(_role.getRoleName());
		}

		return _respUser;
	}

	@Override
	public List<User> getUserListByRecommendFrom(String recommendFrom) {
		// List<MyattentionTalent> myattentionTalentList = new
		// ArrayList<MyattentionTalent>();
		List<User> userList = userMapper.selectUserListByRecommendFrom(recommendFrom);
		/*
		 * for (User user : userList) { MyattentionTalent myattentionTalent = new
		 * MyattentionTalent(); User user1 =
		 * userMapper.selectUserEntityById(user.getId());
		 * myattentionTalent.setUserId(user.getId());
		 * myattentionTalent.setNickName(user1.getNickName());
		 * myattentionTalent.setUserName(user1.getUserName());
		 * myattentionTalent.setPicture(user1.getPicture());
		 * myattentionTalent.setBindRecommendMode(user1.getBindRecommendMode());
		 * myattentionTalent.setCreateTime(null == user1.getLastBindTime() ? "" :
		 * user1.getLastBindTime().substring(0, 19));
		 * myattentionTalentList.add(myattentionTalent); }
		 */
		return userList;
	}

	@Override
	public void cacheUser(Long userId) {
		if (userId == null || userId == 0)
			return;
		final Long _userId = userId;
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				// 缓存用户主信息
				updateUserCacheByUserId(_userId);
				// 缓存用户信息user_info
				cacheUserInfoByUserId(_userId);
				//

			}
		});
	}
}